package com.cqkjxy.commons.services;

import com.cqkjxy.commons.dao.AbstractEntityDao;
import com.cqkjxy.commons.entities.AbstractEntity;
import com.cqkjxy.commons.repositories.AbstractRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

@Service
@Transactional(readOnly = true)
public abstract class AbstractService<T extends AbstractEntity, R extends AbstractRepository<T>, D extends AbstractEntityDao<T, R>> {

    //  Fields
    @PersistenceContext
    protected EntityManager entityManager;

    //  Abstract methods
    protected abstract D getDao();

    //  Public methods
    public T findOne(Integer id) {
        return getDao().findOne(id);
    }

    public Page<T> findList(int page, int pageSize) {
        return getDao().findAllOrderByDefault(PageRequest.of(page, pageSize));
    }

    public List<T> findList() {
        return (List<T>) getDao().findAllOrderByDefault();
    }

    @Transactional(readOnly = false)
    public void delete(int id) {
        getDao().delete(id);
    }
}
